import { MenuOutlined } from '@ant-design/icons';
import { Button, Form, Input, Modal, Space, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { arrayMoveImmutable } from 'array-move';
import React, { useState } from 'react';
import type { SortableContainerProps, SortEnd } from 'react-sortable-hoc';
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import "./index.less";
import { productTagTypes } from '@/constants/types';
import { useRequest } from 'ahooks';
import { fetchLpsLineTagList, enableLpsLineTag, disableLpsLineTag, lpsLineTagAdd, lpsLineTagUpdate, lineTagSort } from '../services';
import { useComponentDidMount } from '@/hooks';
import ProductTagUpdate from '../modals/ProductTagUpdate';
import ProductTagDetail from '../modals/ProductTagDetail';
import XlTableDictColumn from '@/components/Table/XlTableDictColumn';

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  index: number;
}

const DragHandle = SortableHandle(() => <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />);

const SortableItem = SortableElement((props: React.HTMLAttributes<HTMLTableRowElement>) => (
  <tr {...props} />
));
const SortableBody = SortableContainer((props: React.HTMLAttributes<HTMLTableSectionElement>) => (
  <tbody {...props} />
));

const TagManage: React.FC = () => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<productTagTypes | null>(null);
  const [dataSource, setDataSource] = useState<productTagTypes []>([]);
  const {loading, runAsync} = useRequest(fetchLpsLineTagList, {manual: true});
  const {loading: addLoading, runAsync: addApi} = useRequest(lpsLineTagAdd, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(lpsLineTagUpdate, {manual: true});
  
  const [detailVisible, setDetailVisible] = useState<boolean>(false);


  const search = () => {
    const params = form.getFieldsValue();
    runAsync({tagName: params.tagName || ''}).then(res => {
      setDataSource(res || []);
    });
  }


  const enableTag = (record: productTagTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定启用标签',
      onOk: () => {
        enableLpsLineTag({id: record.id}).then(res => {
          if (res?.code === '0') {
            search();
          }
        })
      }
    });
  }
  const disableTag = (record: productTagTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定禁用标签',
      onOk: () => {
        disableLpsLineTag({id: record.id}).then(res => {
          if (res?.code === '0') {
            search();
          }
        })
      }
    });
  }

  const handleAdd = () => {
    setVisible(true);
  }

  const handleEdit = (record: productTagTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }

  const handleRelationProduct = (record: productTagTypes) => {
    setCurrentRow(record);
    setDetailVisible(true);
  }

  const sortData = (data: productTagTypes []) => {
    lineTagSort({ids: data.map(v => v.id)}).then(
      () => {
        search();
      }
    )
  }

  const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
    if (oldIndex !== newIndex) {
      const newData = arrayMoveImmutable(dataSource.slice(), oldIndex, newIndex).filter(
        (el: DataType) => !!el,
      );
      setDataSource(newData);
      sortData(newData)
    }
  };

  const DraggableContainer = (props: SortableContainerProps) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow: React.FC<any> = ({ className, style, ...restProps }) => {
    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex(x => x.id === restProps['data-row-key']);
    return <SortableItem index={index} {...restProps} />;
  };


  const contentProps = {
    visible,
    title: currentRow ? '编辑标签' : '新增标签',
    currentRow,
    loading: addLoading || updateLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: productTagTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        contentProps.onCancel();
        search();
      }
    }
  }

  const detailProps = {
    visible: detailVisible,
    title: '关联产品',
    currentRow,
    onCancel: () => {
      setDetailVisible(false);
      setCurrentRow(null);
    }
  }

  
  const columns: ColumnsType<productTagTypes> = [
    {
      title: '排序',
      dataIndex: 'sort',
      width: 80,
      key: "sort",
      className: 'drag-visible',
      render: () => <DragHandle />,
    },
    {
      title: '标签名称',
      width: 150,
      dataIndex: 'name',
      key: "name",
    },
    {
      title: '营销标签',
      width: 150,
      ellipsis: true,
      dataIndex: 'marketingTags',
      key: "marketingTags",
    },
    {
      title: '状态',
      width: 120,
      dataIndex: 'status',
      key: "status",
      render: (_, record) => <span>{+record?.status === 1 ? '禁用' : '启用'}</span>
    },
    {
      title: '标签可见',
      width: 120,
      dataIndex: 'disFlag',
      key: "disFlag",
      render: (_, record) => <XlTableDictColumn value={record?.dispFlag} type="dispFlag" />
    },
    {
      title: '条件',
      dataIndex: 'conditionList',
      ellipsis: true,
      key: "conditionList",
      render: (_, record) => {
        return (
          <Space direction="horizontal" style={{flexWrap: 'wrap'}}>
            {
              record?.conditionList?.map(v => (
                <div style={{marginRight: 30}}>{v.conditionName}: {v.conditionDesc}</div>
              ))
            }  
          </Space>
        )
      }
    },
    {
      title: '创建时间',
      width: 180,
      key: "createTime",
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      width: 120,
      key: "createBy",
      dataIndex: 'createBy',
    },
    {
      title: '操作',
      dataIndex: 'options',
      fixed: 'right',
      key: "options",
      width: 250,
      render: (_, record: productTagTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleRelationProduct(record)}>关联产品</Button>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            {String(record?.status) === '1' && <Button type="link" onClick={() => enableTag(record)}>启用</Button>}
            {String(record?.status) === '0' && <Button type="link" onClick={() => disableTag(record)}>禁用</Button>}
          </Space>
        )
      }
    },
  ];

  useComponentDidMount(() => {
    search();
  })

  return (
    <>
      <Form form={form} layout='inline'>
        <Form.Item label="标签名称" name="tagName">
          <Input />
        </Form.Item>
        <Space>
          <Button type="default" onClick={() => form.resetFields()}>重置</Button>
          <Button type='primary' onClick={() => search()}>查询</Button>
          <Button type="primary" onClick={() => handleAdd()}>新增分类标签</Button>
        </Space>
      </Form>
      <Table
        className='mt15'
        bordered
        pagination={false}
        dataSource={dataSource}
        columns={columns}
        rowKey="id"
        loading={loading}
        components={{
          body: {
            wrapper: DraggableContainer,
            row: DraggableBodyRow,
          },
        }}
      />
      {visible && <ProductTagUpdate {...contentProps} />}
      {detailVisible && <ProductTagDetail {...detailProps} />}
    </>
  );
};

export default TagManage;